<template>
    <Modal :value="show" @on-visible-change="setVisibility" title="取消工单">
        <Form :label-width="100" class="padding-right-20" v-if="ticket">
            <FormItem label="工单编号：">{{ticket.ticket_sn}}</FormItem>

            <FormItem label="房源地址：">{{concatLocation(ticket.home_info)}}</FormItem>

            <FormItem label="取消原因：">
                <Input type="textarea" v-model="description"></Input>
            </FormItem>
        </Form>

        <Row slot="footer">
            <Button @click="setVisibility(false)" type="text">取消</Button>
            <Button :loading="loading" @click="handleSubmit" type="primary">确定</Button>
        </Row>
    </Modal>
</template>

<script>
/**
 *  工单 - 取消工单
 */
import util from '@/libs/util'
import { http, api } from '@/libs/http'

export default {
  name: 'merchant-cancel-modal',
  props: {
    show: Boolean,
    ticket: Object
  },
  data () {
    return {
      loading: false,
      description: ''
    }
  },
  watch: {
    show (n) {
      if (n) {
      } else {
        this.description = ''
        setTimeout(() => {
          this.$emit('update:ticket', null)
        }, 500)
      }
    }
  },
  methods: {
    concatLocation: util.concatAddress,
    setVisibility (val) {
      this.$emit('update:show', val)
    },
    async checkInstall () {
      const { ticket } = this
      if (ticket.service_type !== 1) return false
      const detail = await http.fetch(this, api.ticket_info, [ticket.id], { service_type: 1 })
      if (!detail) return true
      if (detail.ticket_install_devices && detail.ticket_install_devices.length > 0) {
        this.$Message.info('请先解绑工单上的设备，再取消工单')
        return true
      }
      return false
    },
    async handleSubmit () {
      try {
        this.loading = true
        const ticketHasDevices = await this.checkInstall()
        if (ticketHasDevices) return
        if (!this.description) {
          this.$Message.info('请填写取消原因')
          return
        }
        const res = await http.req(api.ticket_close, [this.ticket.id], { description: this.description })
        if (res) {
          this.$Message.success('操作成功')
          this.$emit('refresh')
          this.setVisibility(false)
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>